package com.gitee.dupe.file.controller;


import cn.hutool.core.lang.Dict;
import com.gitee.dolt.annotation.log.SysLog;
import com.gitee.dolt.annotation.security.PreAuth;
import com.gitee.dolt.boot.controller.DeleteController;
import com.gitee.dolt.boot.controller.QueryController;
import com.gitee.dolt.boot.controller.SuperSimpleController;
import com.gitee.dolt.core.base.Result;
import com.gitee.dolt.core.util.BizAssert;
import com.gitee.dupe.common.properties.DupeProperties;
import com.gitee.dupe.file.entity.Attachment;
import com.gitee.dupe.file.service.IAttachmentService;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 附件表 前端控制器
 * </p>
 *
 * @author LYH
 */
@RestController
@RequestMapping("/b/attachment")
@Slf4j
@Api(value = "附件", tags = "附件")
@Validated
@PreAuth(replace = "b:attachment:")
@RequiredArgsConstructor
public class AttachmentController extends SuperSimpleController<Attachment, IAttachmentService>
        implements QueryController<Attachment, Long, Attachment>, DeleteController<Attachment, Long> {

    private final DupeProperties dupeProperties;

    @Override
    public Result handlerDelete(List<Long> ids) {
        baseService.handlerDelete(ids);
        return Result.ok();
    }

    /**
     * 上传文件
     */
    @ApiOperation(value = "附件上传", notes = "附件上传")
    @PostMapping(value = "/upload")
    public Result upload(@RequestParam(value = "file") MultipartFile file) {
        BizAssert.isTrue(!file.isEmpty(), "请求中必须至少包含一个有效文件");
        Attachment attachment = baseService.upload(file);
        Long duration = attachment.getDuration();
        return Result.ok(Dict.of("id", attachment.getId(), "url", attachment.getUrl()
                , "submittedFileName", attachment.getSubmittedFileName(), "uri", attachment.getUri(),
                "size", attachment.getSize(), "duration", duration, "size2", attachment.getSize2()));
    }


    /**
     * 下载一个文件或多个文件打包下载
     *
     * @param ids 文件id
     */
    @ApiOperation(value = "附件下载", notes = "根据附件id下载多个打包的附件")
    @GetMapping(value = "/download")
    @SysLog
    public void download(
            @ApiParam(name = "ids[]", value = "文件id 数组")
            @RequestParam(value = "ids[]") List<Long> ids,
            HttpServletRequest request, HttpServletResponse response) {
        BizAssert.notEmpty(ids, "附件id不能为空");
        baseService.download(request, response, ids);
    }

    @ApiOperation(value = "资源访问前缀")
    @GetMapping("/uri-prefix")
    public Result getUriPrefix() {
        return Result.ok(dupeProperties.getFile().getUriPrefix());
    }


}
